(function() {
    var connect = function() {
        window.socket = new WebSocket("ws://"+location.host+"/websocket", "ios.play-ios");
    
        window.addEvent("domready", function() {
            var body = document.id(document.body);
            var pairingnumber = document.id("pairingnumber");

            if(!Browser.Features.websockets) {
                body.set("class", "nowebsockets");
            }

            socket.addEvents({
                open: function() {
                    body.set("class", "unpaired");
                },
                message: function(e) {
                    var message = e.data;
                    if(message == "/Unpaired") {
                        body.set("class", "unpaired");
                    } else if(message == "/Paired") {
                        body.set("class", "paired");
                        pairingnumber.set("text", "");
                    } else if(message == "/InvalidPairingNumber") {
                        alert("Pairing number is invalid!");
                    }
                },
                close: function() {
                    body.set("class", "noconnection");
                }
            });
        });
    };
    connect();

    window.addEvent("domready", function() {
        document.id("reconnect").addEvent("touch", connect);

        var pairingnumber = document.id("pairingnumber");
        var pair = function() {
            var number = pairingnumber.get("text");
            while(number.length < 4) {
                number = "0" + number;
            }
            socket.send("/PairingNumber:" + number);
        }
        document.id("ok").addEvent("touch", pair);
        $$(".number").addEvent("touch", function() {
            var oldnumber = pairingnumber.get("text");
            var newnumber = oldnumber + this.get("text");
            pairingnumber.set("text", newnumber);
            if(newnumber.length >= 4) {
                pair();
            }
        });
        document.id("back").addEvent("touch", function() {
            var oldnumber = pairingnumber.get("text");
            if(oldnumber.length) {
                var newnumber = oldnumber.substr(0, oldnumber.length-1);
                pairingnumber.set("text", newnumber);
            }
        });
    });
})();